package com.central.apps.handler.MaterialInventory;

import cn.hutool.core.map.MapUtil;
import com.central.app.common.base.BaseHandler;
import com.central.app.common.constant.AppConstant;
import com.central.app.service.HandlerService;
import com.central.apps.dao.MaterialInventory.outWarehouseDao;
import com.central.apps.handler.base.LvBaseHandler;
import com.central.app.common.util.BLuntil;
import com.central.apps.service.IInventoryService;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.auth.details.LoginAppUser;
import com.central.common.util.SysUserUtil;
import com.central.common.util.ToolUtil;
import com.central.common.web.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
//退库管理
public class OutWarehouseHandler extends LvBaseHandler {
    @Autowired
    private HandlerService handlerService;

    @Override
    public Object operate(String app, String type, Map<String, Object> params) throws Exception {
        if ("returnApp".equals(app)) {
            if ("getReturnnum".equals(type)) {
                String invusenum = MapUtils.getString(params, "invusenum");
                int page = 1;
                int limit = 10;
                if (MapUtils.getInteger(params, AppConstant.BIZ_QUERY_PAGE) != null && MapUtils.getInteger(params, AppConstant.BIZ_QUERY_LIMIT) != null) {
                    page = MapUtil.getInt(params, AppConstant.BIZ_QUERY_PAGE);
                    limit = MapUtil.getInt(params, AppConstant.BIZ_QUERY_LIMIT);
                }
                Map<String, Object> map = handlerService.findOneBySql("SELECT invusenum FROM gq_return WHERE returnnum = '" + invusenum + "'");
                if (map != null && !map.isEmpty()) {
                    String invusenum1 = MapUtils.getString(map, "invusenum");
                    return handlerService.pageList(page, limit, "SELECT\n" +
                            "\ta.itemnum,\n" +
                            "\ta.quantity,\n" +
                            "\ta.wonum,\n" +
                            "\ta.binnum,\n" +
                            "\ta.lotnum,\n" +
                            "\ta.locations, \n" +
                            "\ta.unitcost, \n" +
                            "\ta.linecost \n" +
                            "FROM\n" +
                            "\tgq_invuseline a\n" +
                            "WHERE\n" +
                            "\tinvusenum = '" + invusenum1 + "' \n" +
                            "\tAND (a.itemnum,a.binnum,a.lotnum,a.locations) NOT IN (\n" +
                            "\tSELECT\n" +
                            "\t\tb.itemnum,\n" +
                            "\t\tb.binnum,\n" +
                            "\t\tb.tolot,\n" +
                            "\t\tb.locations\n" +
                            "\tFROM\n" +
                            "\t\tgq_returnline b\n" +
                            "WHERE\n" +
                            "\tinvusenum = '" + invusenum + "')");
                }
            } else if ("getreturnitem".equals(type)) {
                //退库申请，选择物料逻辑
                String returnnum = MapUtils.getString(params, "returnnum");//退货编号
                String invusenum = MapUtils.getString(params, "invusenum");//出库编号
                String location = MapUtils.getString(params, "location");//库房
                String subjectno = MapUtils.getString(params, "subjectno");//课题号
                String taskid = MapUtils.getString(params, "taskid");//任务
                String sql = "select t.*,b.applicant,b.applicantid from gq_itemapplyline t left join gq_itemapply b on t.glnum=b.itemapplynum where t.delflag = '0' ";
                StringBuilder sbl = new StringBuilder();
                sbl.append(sql);
                //选出库单
                if (StringUtils.isNotBlank(invusenum)) {
                    sbl.append(" and t.glnum = '" + invusenum + "'");
                }
                if(StringUtils.isNotBlank(location)){
                    sbl.append(" and t.locations = '" + location + "'");
                }

                if (StringUtils.isNotBlank(subjectno)) {
                    sbl.append(" and b.subjectno = '" + subjectno + "'");
                }

                if (StringUtils.isNotBlank(taskid)) {
                    sbl.append(" and b.taskid = '" + taskid + "'");
                }

                //主表未保存，选子表后台不好判断子表选重
//                sbl.append(" and t.id not in (select itemapplylineid from gq_returnline where invusenum = '" + returnnum + "')");
                sbl.append(" and b.status = '已核准' and reinvenantity>0");

                int page = 1;
                int limit = 10;
                if (MapUtils.getInteger(params, AppConstant.BIZ_QUERY_PAGE) != null && MapUtils.getInteger(params, AppConstant.BIZ_QUERY_LIMIT) != null) {
                    page = MapUtil.getInt(params, AppConstant.BIZ_QUERY_PAGE);
                    limit = MapUtil.getInt(params, AppConstant.BIZ_QUERY_LIMIT);
                }

                PageResult<Map<String, Object>> pageInfo = handlerService.pageList(page, limit, sbl.toString());
                List<Map<String, Object>> list = pageInfo.getData();
                String count = "0";//

                //根据出库编号查出库id
                Map<String, Object> iaMap = handlerService.findOneBySql("select id from gq_itemapply where itemapplynum = '" + invusenum + "'");
                if (CollectionUtils.isNotEmpty(list)) {
                    for (Map<String, Object> map : list) {
                        String isvaluable = MapUtils.getString(map, "isvaluable");
                        String lotnum = MapUtils.getString(map, "lotnum");
                        String quantity = MapUtils.getString(map, "quantity");
                        //判断是否贵重
                        if ("贵重".equals(isvaluable)) {
                            if (StringUtils.isNotBlank(invusenum)) {
                                //填写了出库编号
                                List<Map<String, Object>> bySql1 = handlerService.findBySql("select outquantity  from gq_materialusenew where outboundorderid = '" + MapUtils.getString(iaMap, "id") + "' and materialgoing = '未使用' and lotnum = '" + lotnum + "'");
                                if(CollectionUtils.isNotEmpty(bySql1)){
                                    count = MapUtils.getString(bySql1.get(0), "outquantity");//可退数量;
                                }
                            } else {
                                //没选出库编号，只选了库房，就按库房里所有的
                                //查我的物料未使用的
                                List<Map<String, Object>> bySql1 = handlerService.findBySql("select outquantity from gq_materialusenew where lotnum = '" + lotnum + "' and materialgoing = '未使用'");
                                if(CollectionUtils.isNotEmpty(bySql1)){
                                    count = MapUtils.getString(bySql1.get(0), "outquantity");//可退数量
                                }
                            }
                        } else {
                            count = quantity;
                        }
                        map.put("returnablequantity", count);
                    }

                    return pageInfo;
                }
            }
        }
        return super.operate(app, type, params);
    }

    @Override
    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if ("returnApp".equals(app)) {
            if ("gq_returnline".equals(objName)) {
                // String invusenum = MapUtils.getString(data, "invusenum");
                if (isUpdate == false) {
                    String quantity1 = MapUtils.getString(data, "returnablequantity");
//                String createtime = MapUtils.getString(data, "createtime");
//                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//                Date createtime1 = format.parse(createtime);
                    data.put("bunber", quantity1);
                    data.put("actualdate", new Date());
                }

                // handlerService.insert("gq_returnline", data);
//                List<Map<String, Object>> bySql = handlerService.findBySql("select invusenum from gq_return where  returnnum ='" + invusenum + "'");
//                if (CollectionUtils.isNotEmpty(bySql)){
//                    for (int i=0;i<bySql.size();i++){
//                        Map<String, Object> map = bySql.get(i);
//                        String invusenum1 = MapUtils.getString(map, "invusenum");
//                        List<Map<String, Object>> bySql1 = handlerService.findBySql("SELECT quantity,lotnum,binnum,itemnum,locations from gq_invuseline where invusenum = '" + invusenum1 + "'");
//                        if (CollectionUtils.isNotEmpty(bySql1)){
//                            for (Map<String, Object> map1 : bySql1) {
//                                Integer quantity = MapUtils.getInteger(map1, "quantity");
//                                String lotnum = MapUtils.getString(map1, "lotnum");
//                                String binnum = MapUtils.getString(map1, "binnum");
//                                String itemnum = MapUtils.getString(map1, "itemnum");
//                                String locations = MapUtils.getString(map1, "locations");
//                                handlerService.updateBySql("\tUPDATE gq_returnline set bunber= " + quantity + " where invusenum = '" + invusenum + "' and itemnum='"+itemnum+"' and binnum='"+binnum+"' and tolot='"+lotnum+"' and locations='"+locations+"'");
//                                handlerService.updateBySql("\tUPDATE gq_returnline set actualdate = createtime where invusenum = '" + invusenum + "' and itemnum='"+itemnum+"' and binnum='"+binnum+"' and tolot='"+lotnum+"' and locations='"+locations+"'");
//                            }
//                        }
//                    }
//                }
            }
        }
        super.beforSave(app, objName, data, isUpdate);
    }
//    @Override
//    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
//        if ("returnApp".equals(app)){
//            if ("gq_returnline".equals(objName)){
//                String invusenum = MapUtils.getString(data, "invusenum");
//                List<Map<String, Object>> bySql = handlerService.findBySql("SELECT bunber,unitcost,linecost from gq_returnline where invusenum = '" + invusenum + "'");
//                if (CollectionUtils.isNotEmpty(bySql)){
//                    for (int i=0;i<bySql.size();i++){
//                        Map<String, Object> map = bySql.get(i);
//                        Integer bunber = MapUtils.getInteger(map, "bunber");//数量
//                        Float unitcost = MapUtils.getFloat(map, "unitcost");//单价
//                        Float linecost = MapUtils.getFloat(map, "linecost");//合计
//                        if (isUpdate==true){
//                            handlerService.updateBySql("\tUPDATE gq_returnline set linecost=unitcost*bunber where invusenum = '"+invusenum+"'\n");
//                        }else {
//                            handlerService.updateBySql("\tUPDATE gq_returnline set linecost=unitcost*1 where invusenum = '"+invusenum+"'\n");
//                        }
//                    }
//                }
//            }
//        }
//        super.afterSave(app, objName, data, isUpdate);
//    }


    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
        String msg = "";
        if (flowNode.getId().equals("submit")) {
            List<Map<String, Object>> bySql = handlerService.findBySql("select returnnum,invusenum,location from gq_return where id =" + id);
            String returnnum = MapUtils.getString(bySql.get(0), "returnnum");
            String invusenum = MapUtils.getString(bySql.get(0), "invusenum");//出库编号
            String location = MapUtils.getString(bySql.get(0), "location");
            List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_returnline where invusenum ='" + returnnum + "'");
            if (ToolUtil.isEmpty(bySql1)) {
                msg = "子表数据为空,无法提交审批";
            } else {
                for (int i = 0; i < bySql1.size(); i++) {
                    Map<String, Object> map = bySql1.get(i);
                    String itemnum = MapUtils.getString(map, "itemnum");
                    String tolot = MapUtils.getString(map, "tolot");
                    Float bunber1 = MapUtils.getFloat(map, "bunber");
                    String itemapplylineid = MapUtils.getString(map, "itemapplylineid");//出库申请行id
                    float quantity = 0;
//                    List<Map<String, Object>> bySql2 = handlerService.findBySql("select t.bunber from gq_returnline t left join gq_return a on t.invusenum=a.returnnum where t.itemnum='" + itemnum + "' and t.tolot='" + tolot + "' and a.status!='已审批' and a.invusenum='"+invusenum+"' and a.location='"+location+"'");
//                    if(CollectionUtils.isNotEmpty(bySql2)){
//                        for (int j=0;j<bySql2.size();j++){
//                            Map<String, Object> map1 = bySql2.get(j);
//                            Float bunber = MapUtils.getFloat(map1, "bunber");
//                            quantity=quantity+bunber;//总退库数量
//                        }
                    List<Map<String, Object>> bySql4 = handlerService.findBySql("select t.* from gq_returnline t left join gq_return a on t.invusenum=a.returnnum where t.itemnum='" + itemnum + "' and t.tolot='" + tolot + "'  and t.itemapplylineid='" + itemapplylineid + "' and a.location='" + location + "' and a.status!='新建' and a.status!='已作废' and a.status!='已审批'");
                    if (CollectionUtils.isNotEmpty(bySql4)) {
                        for (int j = 0; j < bySql4.size(); j++) {
                            Map<String, Object> map2 = bySql4.get(j);
                            Float bunber = MapUtils.getFloat(map2, "bunber");
                            quantity = quantity + bunber;
                        }
                        bunber1 = bunber1 + quantity;
                    }
                        List<Map<String, Object>> bySql3 = handlerService.findBySql("select * from gq_itemapplyline where id='" + itemapplylineid + "' and itemnum='" + itemnum + "' and lotnum ='" + tolot + "'");
                        Float grantqty = (float) 0;
                        if (CollectionUtils.isNotEmpty(bySql3)) {
                            Map<String, Object> map1 = bySql3.get(0);
                            grantqty = MapUtils.getFloat(map1, "reinvenantity");
                        }
                        if (grantqty.compareTo(bunber1) < 0) {
                            int y = i + 1;
                            float grantqty1 = grantqty - quantity;
                            if (grantqty1<=0){
                                return "退库物料第" + y + "条数据中部分物料被人占用，当前出库剩余数量不足，请重新选择物料！";
                            }else {
                                return "退库物料第" + y + "条数据中部分物料被人占用，当前出库剩余" + grantqty1 + "，请重新选择物料！";
                            }

                        }


                }
            }
        }
        return msg;
    }

    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {
        if (flowNode.getId().equals("kfgly")){
            // 审核通过后退库库存
            boolean flag = op.isFlag();//判断是否审核通过
            if (flag){
//                List<Map<String, Object>> bySql = handlerService.findBySql("select instonum from gq_instorage order by createtime desc limit 1");
//                String instonum =MapUtils.getString(bySql.get(0),"instonum");
//                if(instonum.equals("") || instonum ==null){
//                    instonum ="10001";
//                }else{
//                    Integer num =Integer.parseInt(instonum);
//                    num++;
//                    instonum=Integer.toString(num);
//                }
                List<Map<String, Object>> bySql1 = handlerService.findBySql("select * from gq_return where id =" + id);
                String type =MapUtils.getString(bySql1.get(0),"type");
                if("返厂维修".equals(type)){
                    handerDepotRepair(bySql1);

                }else{
                    //之前逻辑不变，方法抽取出来
                    handlerType(bySql1);
                }
            }
        }
    }

    //退库为返厂维修，自动生成入库记录，同时生成一张出库记录，无需库管员再编制个人领用进行返厂维修出库；对库存台账余量不进行操作。直接生成出入库记录
    private void handerDepotRepair(List<Map<String, Object>> bySql1) {
        //生成入库记录
        String location =MapUtils.getString(bySql1.get(0),"location");
        String locationdesc =MapUtils.getString(bySql1.get(0),"locationdesc");
        String returnnum =MapUtils.getString(bySql1.get(0),"returnnum");
        String subjectno = MapUtils.getString(bySql1.get(0), "subjectno");//课题号
        String description1 = MapUtils.getString(bySql1.get(0), "description");

        List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_returnline where invusenum ='" + returnnum + "'");
        if(CollectionUtils.isNotEmpty(bySql2)){
            for (Map<String, Object> map : bySql2) {
                String itemnum =MapUtils.getString(map,"itemnum");
                String deptcode = MapUtils.getString(map, "deptcode");
                String createuser = MapUtils.getString(map, "createuser");
                Float bunber =MapUtils.getFloat(map,"bunber");//退库数量
                String binnum =MapUtils.getString(map,"binnum");//货位
                String tolot =MapUtils.getString(map,"tolot");//批次
                String taskid = MapUtils.getString(map, "taskid");
                String proid = MapUtils.getString(map, "proid");
                String unitcost1 = MapUtils.getString(map, "unitcost");
                BigDecimal unitcost = new BigDecimal(unitcost1);
                String linecost1 = MapUtils.getString(map, "linecost");
                BigDecimal linecost = new BigDecimal(linecost1);
                List<Map<String, Object>> bySql3 = handlerService.findBySql("select * from gq_item where itemnum ='" + itemnum + "'");
                String description =MapUtils.getString(bySql3.get(0),"description");
                String unit =MapUtils.getString(bySql3.get(0),"unit");

                String instonumNew="";//入库编号
                List<Map<String, Object>> bySql7 = handlerService.findBySql("SELECT instonum from gq_matusetrans where instonum  LIKE '%CDFI%' order by instonum desc limit 1");
                if(CollectionUtils.isNotEmpty(bySql7)){
                    Map<String, Object> map7 = bySql7.get(0);
                    String instonum1 = MapUtils.getString(map7, "instonum");
                    int integer = Integer.valueOf(instonum1.substring(instonum1.length() - 8));
                    integer++;
                    instonumNew="CDFI"+integer;
                }else{
                    instonumNew="CDFI10000001";
                }
                handlerService.updateBySql("insert into gq_matusetrans (instonum,instodesc,itemnum,itemdesc,storenum,storedesc,lotnum,quantity,type,unitcost,linecost,createtime,taskid,proid,deptcode,createuser,unit,binnum,subjectno) values('"+instonumNew+"','"+description1+"','"+itemnum+"','"+description+"','"+location+"','"+locationdesc+"','"+tolot+"','"+bunber+"','退回',"+unitcost+","+linecost+",now(),'"+taskid+"','"+proid+"','"+deptcode+"','"+createuser+"','"+unit+"','"+binnum+"','"+subjectno+"')");

                String outonumNew="";//出库编号
                List<Map<String, Object>> bySql9 = handlerService.findBySql("SELECT instonum from gq_matusetrans where instonum  LIKE '%CDFO%' order by instonum desc limit 1");
                if(CollectionUtils.isNotEmpty(bySql9)){
                    Map<String, Object> map1 = bySql9.get(0);
                    String instonum = MapUtils.getString(map1, "instonum");
                    int integer = Integer.valueOf(instonum.substring(instonum.length() - 8));
                    integer++;
                    outonumNew="CDFO"+integer;
                }else{
                    outonumNew="CDFO10000001";
                }
                handlerService.updateBySql("insert into gq_matusetrans (subjectno,deptcode,instonum,instodesc,itemnum,itemdesc,quantity,unit,createtime,createuser,storenum,storedesc,lotnum,type,unitcost,linecost,proid,taskid,binnum,receiptnum) values('"+subjectno+"','"+deptcode+"','"+outonumNew+"','"+description1+"','"+itemnum+"','"+description+"',"+bunber+",'"+unit+"',now(),'"+createuser+"','"+location+"','"+locationdesc+"','"+tolot+"','返厂维修',"+unitcost+","+linecost+",'"+proid+"','"+taskid+"','"+binnum+"','"+returnnum+"')");
            }
        }
    }

    private void handlerType(List<Map<String, Object>> bySql1) {
        String location =MapUtils.getString(bySql1.get(0),"location");
        String locationdesc =MapUtils.getString(bySql1.get(0),"locationdesc");
        String invusedesc =MapUtils.getString(bySql1.get(0),"invusedesc");
        // invusedesc =invusedesc+"退库申请";
        String invusenum = MapUtils.getString(bySql1.get(0), "invusenum");
        String createuserdesc =MapUtils.getString(bySql1.get(0),"createuserdesc");
        String createtime = MapUtils.getString(bySql1.get(0), "createtime");
        //handlerService.updateBySql("insert into gq_instorage (instonum,instodesc,warehousenum,storedesc,createuser,createtime,status)values('"+instonum+"','"+invusedesc+"','"+location+"','"+locationdesc+"','"+createuser+"',now(),'审批通过')");
        String returnnum =MapUtils.getString(bySql1.get(0),"returnnum");
        String subjectno = MapUtils.getString(bySql1.get(0), "subjectno");//课题号
        String description1 = MapUtils.getString(bySql1.get(0), "description");
        List<Map<String, Object>> bySql2 = handlerService.findBySql("select * from gq_returnline where invusenum ='" + returnnum + "'");
        for(Map<String,Object> map :bySql2){
            String itemnum =MapUtils.getString(map,"itemnum");
            String deptcode = MapUtils.getString(map, "deptcode");
            String createuser = MapUtils.getString(map, "createuser");
            Float bunber =MapUtils.getFloat(map,"bunber");//退库数量
            String actualdate =MapUtils.getString(map,"actualdate");//退回时间
            String tablist =MapUtils.getString(map,"tablist");
            String binnum =MapUtils.getString(map,"binnum");//货位
            String tolot =MapUtils.getString(map,"tolot");//批次
            Float quantity = MapUtils.getFloat(map, "quantity");//出库数量
            String taskid = MapUtils.getString(map, "taskid");
            String proid = MapUtils.getString(map, "proid");
            String unitcost1 = MapUtils.getString(map, "unitcost");
            BigDecimal unitcost = new BigDecimal(unitcost1);
            String linecost1 = MapUtils.getString(map, "linecost");
            BigDecimal linecost = new BigDecimal(linecost1);
            //修改出库申请可退库数量
            String itemapplylineid = MapUtils.getString(map, "itemapplylineid");//出库申请行id
            Float reinvenantity = MapUtils.getFloat(map, "reinvenantity");
            reinvenantity=reinvenantity-bunber;
            handlerService.updateBySql("update gq_itemapplyline set reinvenantity="+reinvenantity+" where id='"+itemapplylineid+"'");
            handlerService.updateBySql("update gq_returnline set reinvenantity="+reinvenantity+" where id='"+itemapplylineid+"'");
            List<Map<String, Object>> bySql3 = handlerService.findBySql("select * from gq_item where itemnum ='" + itemnum + "'");
            String description =MapUtils.getString(bySql3.get(0),"description");
            String unit =MapUtils.getString(bySql3.get(0),"unit");
            List<Map<String, Object>> bySql=null;
            if (taskid==null||taskid==""){
                bySql = handlerService.findBySql("select GRANTQTY from gq_itemapplyline where locations='" + location + "' and itemnum ='" + itemnum + "' and binnum ='" + binnum + "' and lotnum ='" + tolot + "' and proid='" + proid + "'");
            }else {
                bySql = handlerService.findBySql("select GRANTQTY from gq_itemapplyline where locations='" + location + "' and itemnum ='" + itemnum + "' and binnum ='" + binnum + "' and lotnum ='" + tolot + "' and proid='" + proid + "' and taskid='" + taskid + "'");
            }
//                    Float grantqty = MapUtils.getFloat(bySql.get(0), "GRANTQTY");
//                    grantqty = grantqty-bunber;
//                    if (taskid==null||taskid==""){
//                        handlerService.updateBySql("update gq_itemapplyline set GRANTQTY ="+grantqty+"  where locations='" + location + "' and itemnum ='" + itemnum + "' and binnum ='" + binnum + "' and lotnum ='" + tolot + "' and proid='" + proid + "'");
//                    }else {
//                        handlerService.updateBySql("update gq_itemapplyline set GRANTQTY ="+grantqty+"  where locations='" + location + "' and itemnum ='" + itemnum + "' and binnum ='" + binnum + "' and lotnum ='" + tolot + "' and proid='" + proid + "' and taskid='" + taskid + "'");
//                    }
            List<Map<String, Object>> bySql4=null;
            if (taskid==null||taskid==""){
                bySql4= handlerService.findBySql("select * from gq_invbalances where storenum ='" + location + "' and itemnum ='" + itemnum + "' and batchnum ='"+tolot+"' and binnum ='"+binnum+"' and proid='"+proid+"' ");

            }else {
                bySql4= handlerService.findBySql("select * from gq_invbalances where storenum ='" + location + "' and itemnum ='" + itemnum + "' and batchnum ='"+tolot+"' and binnum ='"+binnum+"' and proid='"+proid+"' and taskid='" + taskid + "'");
            }
            Float curbal = MapUtils.getFloat(bySql4.get(0),"curbal");
            curbal=curbal +bunber;
            Float reservedqty = MapUtils.getFloat(bySql4.get(0), "reservedqty");
            Float avblbalance = MapUtils.getFloat(bySql4.get(0),"avblbalance");
            avblbalance =curbal - reservedqty;
            handlerService.updateBySql("update gq_invbalances set curbal ="+curbal+",avblbalance="+avblbalance+" where storenum ='" + location + "' and itemnum ='" + itemnum + "' and batchnum = '" + tolot + "'");
            List<Map<String, Object>> bySql6 = handlerService.findBySql("select * from gq_invbalances where  itemnum  ='" + itemnum + "'and storenum ='" + location + "'");
            float curbal1 = 0;//库存余量
            float avblbalance1 = 0;//可用余量
            if (CollectionUtils.isNotEmpty(bySql6)){
                for (Map<String,Object> objectMap :bySql6){
                    Float curbal2 = MapUtils.getFloat(objectMap, "curbal");
                    curbal1 = curbal1+curbal2;//库存余量
                    Float avblbalance2 = MapUtils.getFloat(objectMap, "avblbalance");
                    avblbalance1 = avblbalance1+avblbalance2;//库存可用余量
                }
                handlerService.updateBySql("update gq_inventory set curbaltotal = " + curbal1 + ", avblbalance = " + avblbalance1 +  " where storenum = '" + location + "' and itemnum = '" + itemnum + "'");
            }
            String instonumNew="";//入库编号
            List<Map<String, Object>> bySql7 = handlerService.findBySql("SELECT instonum from gq_matusetrans where instonum  LIKE '%CDFI%' order by instonum desc limit 1");
            if(CollectionUtils.isNotEmpty(bySql7)){
                Map<String, Object> map7 = bySql7.get(0);
                String instonum1 = MapUtils.getString(map7, "instonum");
                int integer = Integer.valueOf(instonum1.substring(instonum1.length() - 8));
                integer++;
                instonumNew="CDFI"+integer;
            }else{
                instonumNew="CDFI10000001";
            }
            //添加到 出库单记录表
            //写入内容包含：物料编号、物料描述、交易类型（出库）、数量、单位、交易时间（创建时间）、交易处理人（创建人）
//                    List<Map<String, Object>> bySql5 = handlerService.findBySql("select itemdesc,outunit from gq_inventory where itemnum ='" + itemnum + "'");
//                    String itemdesc =MapUtils.getString(bySql5.get(0),"itemdesc");
//                    String outunit =MapUtils.getString(bySql5.get(0),"outunit");
//                    LoginAppUser user = SysUserUtil.getLoginAppUser();
//                    Long id1= user.getId();
//                    String createuserdesc = user.getNickname();
            handlerService.updateBySql("insert into gq_matusetrans (instonum,instodesc,itemnum,itemdesc,storenum,storedesc,lotnum,quantity,type,unitcost,linecost,createtime,taskid,proid,deptcode,createuser,unit,binnum,subjectno) values('"+instonumNew+"','"+description1+"','"+itemnum+"','"+description+"','"+location+"','"+locationdesc+"','"+tolot+"','"+bunber+"','退回',"+unitcost+","+linecost+",now(),'"+taskid+"','"+proid+"','"+deptcode+"','"+createuser+"','"+unit+"','"+binnum+"','"+subjectno+"')");
        }
    }
}
